package GoodsActivityService

import (
	"fmt"
	"gdshop-back-end-go/client-api/app/response/GoodsResp"
	"gdshop-back-end-go/common/entity"
	"github.com/gogf/gf/encoding/gjson"
	"sort"
	"strings"
)

// 计算一条数据优惠比例 ， 只计算 activity_type = 1 和 activity_type = 2 的情况
func clacDiscountRatio(p *entity.GoodsActivity) float64 {
	if p.ActivityType != 1 && p.ActivityType != 2 {
		// 不支持类型，直接返回
		return 0
	}

	// 解析规则
	ruleList, err := AnalysisRule(p.Rules)
	if err != nil {
		panic("解析规则失败：" + err.Error())
	}
	if len(ruleList) < 1 {
		// 防止出错
		panic("解析规则失败：长度为0")
	}

	// 排序，选出最优惠的排在第一位
	sort.Slice(ruleList, func(i, j int) bool {
		return clacDiscountRatioOne(ruleList[i], p.ActivityType) < clacDiscountRatioOne(ruleList[j], p.ActivityType)
	})

	return clacDiscountRatioOne(ruleList[0], p.ActivityType)
}

// 计算单项优惠比例
func clacDiscountRatioOne(one *entity.RulesItem, activityType int) float64 {
	// 减
	if activityType == 2 {
		// 每满减实际就是折扣
		return 1 - float64(one.DiscountNum)/float64(one.ThresholdNum)
	}
	// 折
	if activityType == 1 {
		return float64(one.DiscountNum) / 1000.00
	}

	return 0
}

func GetActivityTagTypeStr(m *entity.GoodsActivity) string {
	// 1打折；2满减；3秒杀价；4送优惠券 5送赠品
	switch m.ActivityType {
	case 1:
		return "满折"
	case 2:
		return "满减"
	case 3:
		return "秒杀"
	case 4:
		return "送券"
	case 5:
		return "赠品"
	}

	return "未知"
}

func getActivityTagRemark(m *entity.GoodsActivity) string {
	if m.Rules == "" {
		return ""
	}
	// 1打折；2满减；3秒杀价；4送优惠券 5送赠品
	remark := ""
	if m.Loop > 0 {
		remark = "每"
	}
	rules := []*GoodsResp.GoodsActivityRuleItem{}
	json, err := gjson.LoadContent(m.Rules)
	if err != nil {
		return err.Error()
	}
	err = json.Structs(&rules)
	if err != nil {
		return err.Error()
	}
	ruleTexts := []string{}
	for _, item := range rules {
		if item.ThresholdNum < 1 {
			ruleTexts = append(ruleTexts, "无门槛")
		} else {
			ruleTexts = append(ruleTexts, remark+"满"+
				(fmt.Sprintf("%.2f", float64(item.ThresholdNum)/float64(100)))+"元")
		}
		switch m.ActivityType {
		case 1:
			ruleTexts = append(ruleTexts, "打"+
				(fmt.Sprintf("%.2f", float64(item.ThresholdNum)/float64(100)))+"折")
			break
		case 2:
			ruleTexts = append(ruleTexts, "可减"+
				(fmt.Sprintf("%.2f", float64(item.ThresholdNum)/float64(100)))+"元")
			break
		}
	}

	return strings.Join(ruleTexts, ",")
}
